package com.hanlink.dsp.ui.broadcast;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;

import com.hanlink.dsp.ui.dialog.MessageDialog;
import com.hanlink.dsp.util.Constants;
import com.qztech.sdk.R;
import com.qztech.sdk.utils.BLog;

/**
 * Created by zhb on 2018/5/15.
 */

public class UploadReceiver extends BroadcastReceiver {
    private Activity mActivity;
    private MessageDialog mDialog;

    public UploadReceiver(Activity activity) {
        mActivity = activity;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BLog.e("upload", Thread.currentThread().getName());
        if (Constants.ACTION_START_UPLOAD.equals(action)) {
            showDialog();
        } else if (Constants.ACTION_STOP_UPLOAD.equals(action)) {
            dismissDialog();
        }

    }

    public void start() {
        IntentFilter filter = new IntentFilter(Constants.ACTION_START_UPLOAD);
        filter.addAction(Constants.ACTION_STOP_UPLOAD);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            mActivity.registerReceiver(this,filter,Context.RECEIVER_EXPORTED);
        }else{
            mActivity.registerReceiver(this, filter);
        }

    }

    public void stop() {
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
        mActivity.unregisterReceiver(this);
    }

    public void pause() {
        dismissDialog();
    }

    private void showDialog() {
        if (mDialog == null) {
            mDialog = new MessageDialog(mActivity);
        }
        mDialog.setMessage(com.hanlink.res.R.string.upload_settings);
        if (!mDialog.isShowing()) {
            mDialog.show();
        }
    }

    private void dismissDialog() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }
}
